/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.ueditor.service;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;

import com.guoyu.project.common.ueditor.UeditorDefaultConfig;
import com.guoyu.project.common.utils.PropertyUtil;

/**
 * @author: libo Date: 17-7-14 Time: 上午11:13
 * @version: \$Id$
 */
public abstract class AbstractHandler implements UeditorHandler {

    public static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd").toFormatter();

    protected final String DOT = ".";

    protected final String UPLOADER_PATH = PropertyUtil.getProperty("uploader.path");
    protected String domain = PropertyUtil.getProperty("domain");

    public String getRelativePath(String fileName) {
        String extension = getExtension(fileName);
        String path = StringUtils.replace(UeditorDefaultConfig.PATH_FORMAT, "{ext}", extension);
        path = StringUtils.replace(path, "{yyyy-mm-dd}", new DateTime().toString(DATE_TIME_FORMATTER));
        path = StringUtils.replace(path, "{time}", String.valueOf(System.currentTimeMillis()));
        path = StringUtils.replace(path, "{rand:6}", RandomStringUtils.randomAlphanumeric(6));
        return getRelativePathPre() + path + DOT + extension;
    }

    public String getRelativePathPre() {
        return UeditorDefaultConfig.FILE_URL_PRE;
    }

    public String getPhysicalPathPre() {
        return UPLOADER_PATH;
    }

    public String getExtension(String fileName) {
        if (StringUtils.INDEX_NOT_FOUND == StringUtils.indexOf(fileName, DOT)) {
            return StringUtils.EMPTY;
        }
        return StringUtils.substringAfterLast(fileName, DOT);
    }

    public String getUrl(String relativePath) {
        return domain + StringUtils.replace(relativePath, "\\", "/");
    }

}
